package com.duoec.dw.lineage.service.analyser.statement;

import com.duoec.dw.lineage.dto.SqoopCommendArgument;
import com.duoec.dw.lineage.dto.statement.SqoopStatement;
import com.duoec.dw.lineage.service.LineageAnalyseService;
import com.duoec.dw.lineage.service.SqoopCommendLineAnalyser;
import com.duoec.dw.lineage.service.SqoopStatementAnalyser;
import com.google.common.base.Splitter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

import java.util.List;
import java.util.Optional;

/**
 * @author xuwenzhen
 */
public abstract class BaseSqoopStatementAnalyser<T extends SqoopStatement> implements SqoopStatementAnalyser<T> {
    private static final Logger logger = LoggerFactory.getLogger(BaseSqoopStatementAnalyser.class);
    protected static final String STR_SQOOP = "sqoop ";

    @Autowired
    @Qualifier("lineageAnalyseServiceDruidImpl")
    protected LineageAnalyseService druidLineageAnalyseService;

    @Autowired
    private List<SqoopCommendLineAnalyser> sqoopCommendLineAnalyserList;

    protected SqoopCommendArgument getArgument(String script) {
        SqoopCommendArgument sqoopArgumentDto = new SqoopCommendArgument();
        Splitter.on("--")
                .trimResults()
                .omitEmptyStrings()
                .split(script)
                .forEach(line -> {
                    Optional<SqoopCommendLineAnalyser> analyserOpt = sqoopCommendLineAnalyserList
                            .stream()
                            .filter(analyser -> line.startsWith(analyser.getStart()))
                            .findFirst();
                    if (analyserOpt.isPresent()) {
                        SqoopCommendLineAnalyser analyser = analyserOpt.get();
                        analyser.analyse(sqoopArgumentDto, line);
                    }
                });

        return sqoopArgumentDto;
    }
}
